<?php
namespace app\jobmanagement\controller;

use app\lib\Dingtalk;
use think\Controller;

use app\constdir\ApiConst;

class Base  extends Controller
{
    protected $Dingtalk;
    protected $access_token;
    protected $userinfo;

    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');//允许所有来源访问
        header('Access-Control-Allow-Method:POST,GET');//允许访问的方式
        //获取企业凭证access_token
        $this->Dingtalk = new Dingtalk();
        $this->access_token = $this->Dingtalk->getAccessToken();
        if(empty($this->access_token)){
            //echo $this->apiError('钉钉官方接口维护中，内部应用暂时无法使用，请见谅',ApiConst::ACCESS_TOKEN_ERROR_CODE);
            echo $this->apiError(ApiConst::ACCESS_TOKEN_ERROR_MSG,ApiConst::ACCESS_TOKEN_ERROR_CODE);
            exit();
        }

        $user_code = input('user_token');//当前用户登录code
        if (!preg_match("/^[0-9,a-z]*$/",$user_code)) {
            echo $this->apiError(ApiConst::AUTH_CODE_FORMAT_ERROR_MSG,ApiConst::AUTH_CODE_FORMAT_ERROR_CODE);
            exit();
        }

        //根据acess_token和code去获取当前登陆用户信息

        $this->userinfo = $this->Dingtalk->getUserInfo($this->access_token, $user_code);
        if(empty($this->userinfo)){
            echo $this->apiError(ApiConst::USER_INFO_ERROR_MSG,ApiConst::USER_INFO_ERROR_CODE);
            exit();
        }else{
            //每次检测数据库中是否存在该用户，没有的话就新增
            $sCommon = model('Common', 'service');
            $sCommon->saveUserInfo($this->userinfo);
            session('dd_user_id', $this->userinfo->userid);
            session('is_sys',$this->userinfo->is_sys ? 1 : 0);
            // 查询数据库
            $user = $sCommon->getUserinfo($this->userinfo->userid);
            if (empty($user)) {
                session('user_level',3);
                session('dept_id',0);
            } else {
                session('user_level', $user['level']);
                session('dept_id', $user['dept_id']);
            }
        }

    }

    /*
     * 成功返回提示
     */
    public function apiSuccess($message , $data = null,$page =null){
        return collection([
            'status' => ApiConst::SUCCESS_CODE,
            'msg' => $message,
            'data' => $data,
            'page' => $page
        ]);
    }

    /*
 * 错误提示
 */
    public function apiError($message,$code = ApiConst::FAILED_CODE,$data=null){
        return collection([
                'status' => $code,
                'msg' => $message,
                'data' => $data,
            ]
        );
    }


    /**
     * 集成成功和错误提示综合处理数据   (看情况选用)
     */

    public function apiSuccessError($info , $page = null){
        if(empty($info['code'])){
            return $this->apiSuccess(ApiConst::SUCCESS_CODE_MSG,$info ,$page);
        }else{
            return $this->apiError($info['msg'],$info['code']);
        }
    }



}
